var express = require('express');
var router = express.Router();
var mongoose = require('mongoose')
var Goods = require('../models/goods')
// ========================坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑坑============================================
// 链接一个不存在的数据库仍然不会报错，而是connect succ 当连接一个不存在的数据库时会新建一个数据库，当你插入数据时则会看到该数据库
mongoose.connect('mongodb://localhost:27017/mall')
mongoose.connection.on('connected',()=>{
  console.log("MongoDB conect succ")
})
mongoose.connection.on('error',()=>{
  console.log("MongoDB conect error")
})
mongoose.connection.on('disconnected',()=>{
  console.log("MongoDB conect disconnected")
})
// 商品列表接口
router.get('/list', function(req, res, next) {
  // 后台分页功能的具体实现========================================
  // 前端传过来的页码
  let page = parseInt(req.param("page"))
  // 前端传递过来的排序方式
  let sort = req.param("sort")
  // 前端传递过来的每页需要展示的数据数
  let pageSize = parseInt(req.param("pageSize"))
  // 前端传过来的价格等级
  let priceLevel = parseInt(req.param("priceLevel"))
  // 价格区间
  var priceGt = ''
  var priceLte = ''
  let skip = (page - 1)*pageSize
  let params = {}
  console.log(priceLevel)
  //  limit(Number):限制获取的数据条数
  //  skip(Number):忽略数据的条数
  if(priceLevel != 4) {
    switch (priceLevel) {
      case 0: priceGt = 0;priceLte = 100;break;
      case 1: priceGt = 100;priceLte = 500;break;
      case 2: priceGt = 500;priceLte = 1000;break;
      case 3: priceGt = 1000;priceLte = 5000;break;
      default:
        break;
    }
    params = {
      salePrice: {
        // $gt: 大于， $lte: 小于
        $gt: priceGt,
        $lte: priceLte
      }
    }
  } 
  let goodsModel = Goods.find(params).skip(skip).limit(pageSize)
  goodsModel.sort({'salePrice':sort})
  goodsModel.exec((err, doc) => {
    if (err) {
        res.json({
          status: '1',
          msg:err.message
        })
    } else {
      res.json({
        status: '0',
        msg: '',
        result: {
          count: doc.length,
          list: doc
        }
      })
    }
  })
});
// 购物车接口
router.post('/cartList', (req,res,next) => {
  var userId = '100000077', productId = req.body.productId
  var User = require('../models/user')

  User.findOne({userId:userId}, (err, userDoc)=> {
    if(err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      // console.log("userDoc: "+ userDoc)
      if(userDoc) {
        let goodsItem = ''
        userDoc.cartList.forEach((item)=> {
          if(item.productId == productId) {
            goodsItem = item
            item.productNum++
          }
        })
        if(goodsItem) {
          userDoc.save((err2, doc2)=>{
            if(err2) {
              res.json({
                status: "1",
                msg: err2.message
              })
            } else {
              res.json({
                status: '0',
                msg: '',
                result: 'succ'
              })
            }
          })
        }else {
          Goods.findOne({productId:productId}, (err1, doc)=>{
            if(err1) {
              res.json({
                status: "1",
                msg: err1.message
              })
            } else { 
              if(doc) {
                // 坑===================================坑
                doc.productNum = 1
                doc.checked = 1
                userDoc.cartList.push(doc)
                userDoc.save((err2, doc2)=>{
                  if(err2) {
                    res.json({
                      status: "1",
                      msg: err2.message
                    })
                  } else {
                    res.json({
                      status: '0',
                      msg: '',
                      result: 'succ'
                    })
                  }
                })
              }
            }
          })
        }
        
      }
    }
  })
})

module.exports = router;
